#include "TKSPStdAfx.h"

#include "DBXDataSetter.h"
#include "DBXDeviceManager.h"

#include <libconfig.hpp>

namespace DBX
{
    namespace Constants
    {
        extern const char *keyDataLabel;
        extern const char *keyDataType;
        extern const char *keyDataValue;
    } // namespace Constants
    class DBXDataSetter::Private
    {
    public:
        Private(DBXDataSetter *p)
            : o(p)
        {}

        void set()
        {
            const Setting &setting = o->getRoot();
            auto count = setting.getLength();
            for(int i = 0; i < count; ++i) {
                auto &item = setting[i];
                std::string label;
                int dataType = -1;
                if(!(item.lookupValue(Constants::keyDataLabel, label) &&
                     item.lookupValue(Constants::keyDataType, dataType))) {
                    continue;
                }
                auto pos = label.find_first_of(".");
                if(pos != std::string::npos) {
                    if(auto manager = DBXDeviceManager::instance()) {
                        if(auto device = manager->find(label.substr(pos))) {
                            device->set(item);
                        }
                    }
                }
            }
        }

    private:
        friend class DBXDataSetter;
        DBXDataSetter *o;
    };

    DBXDataSetter::DBXDataSetter()
        : p(*new Private(this))
    {}

    DBXDataSetter::~DBXDataSetter()
    {
        delete &p;
    }

    void DBXDataSetter::set()
    {
        p.set();
    }
} // namespace DBX